package itsm.isperp.module.controller.api.mobile;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.utils.JsonBuilder;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.solr.SolrKngKnowledgeDTO;
import itsm.isperp.module.service.knowledge.KngKnowledgeCommentService;
import itsm.isperp.module.service.knowledge.KngKnowledgeItemService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 
 * 手机端知识接口控制器
 * 
 * @author zhouhg
 * @date 2014-3-25
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("api/mobile/knowledge")
public class MobileKnowledgeController {

	public static final Logger logger = LoggerFactory
			.getLogger(MobileKnowledgeController.class);

	/**
	 * 根据关键字查询知识库
	 * 
	 * @param keyword
	 *            关键字
	 * @param currentPage
	 *            当前页
	 * @param size
	 *            加载数量
	 * @return
	 */
	@RequestMapping("search")
	@ResponseBody
	public ResultMessage search(String keyword, Integer currentPage,
			Integer size) {
		try {

			if (StringUtils.isEmpty(keyword)) {
				return null;
			}

			KngKnowledgeItemService kngKnowledgeItemService = ContextHolder
					.getSpringBean(KngKnowledgeItemService.class);

			if (size == null || size <= 0) {
				size = 20;
			}

			Pageable pg = new PageRequest(currentPage, size);
			
			Criteria[] cs=null;
			
			List<SolrKngKnowledgeDTO> list = kngKnowledgeItemService
					.searchByKeyword(keyword, pg, cs,null).getContent();

			List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
			for (SolrKngKnowledgeDTO obj : list) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", obj.getId());
				map.put("title", obj.getTitle());
				map.put("contents", obj.getContents());
				map.put("category_name", obj.getCategoryName());
				map.put("publish_date", obj.getPublishDate());
				map.put("commentary_times", obj.getCommentaryTimes());
				map.put("read_times", obj.getReadTimes());
				newList.add(map);
			}

			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(newList));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("知识搜索失败，原因是：" + e.getMessage());
		}
	}

	/**
	 * 根据关键字查询知识库
	 * 
	 * @param id
	 *            知识ID
	 * @return
	 */
	@RequestMapping("knowledgeDetail")
	@ResponseBody
	public ResultMessage knowledgeDetail(String id) {
		try {

			KngKnowledgeItemService kngKnowledgeItemService = ContextHolder
					.getSpringBean(KngKnowledgeItemService.class);

			KngKnowledgeCommentService kngKnowledgeCommentService = ContextHolder
					.getSpringBean(KngKnowledgeCommentService.class);

			kngKnowledgeItemService.increaseReadTimes(id);

			Map<String, Object> model = kngKnowledgeItemService
					.findOneDetailById(id);

			List<Map<String, Object>> comments = kngKnowledgeCommentService
					.findAllDetailByKnowledgeId(id);

			model.put("comments", comments);
			
			String result=JsonBuilder.buildNormalBinder()
          .toJson(model);
			String appConfigAddress=ContextHolder.getConfigByKey("appConfigAddress");
			if(StringUtils.isNotEmpty(appConfigAddress))
			{
			  result=result.replaceAll("uploadFile/ueditor/upload", "http://"+appConfigAddress+"/uploadFile/ueditor/upload");
			}
			

			return ResultMessage.success(result);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("加载知识详情失败，原因是：" + e.getMessage());
		}
	}

	/**
	 * 发表评论
	 * 
	 * @param id
	 *            知识ID
	 * @param comments
	 *            评论内容
	 * @return
	 */
	@RequestMapping("kngComment")
	@ResponseBody
	public ResultMessage kngComment(String id, String comments, String username) {
		try {

			KngKnowledgeCommentService kngKnowledgeCommentService = ContextHolder
					.getSpringBean(KngKnowledgeCommentService.class);
			kngKnowledgeCommentService.addCommont(id, comments, username);

			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson("发表评论成功！"));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("发表评论失败，原因是：" + e.getMessage());
		}
	}

}
